<template>
  <el-form label-width="80px" label-position="right">
    <el-row :gutter="8">
      <el-col :span="6">
        <el-form-item label="数据库" required>
          <el-select style="width: 100%" v-model="modelInfo.callDb" placeholder="切换数据库" :disabled="!$Util.isEmpty(modelInfo.modelId)" @change="dbChange">
            <el-option v-for="option in appContext.allDbs" :key="option.callCmd" :value="option.callCmd" :label="option.dbSchema"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6"><el-form-item label="调用指令" required> <el-input v-model="modelInfo.callCmd" placeholder="调用指令" :disabled="!$Util.isEmpty(modelInfo.modelId)" /></el-form-item></el-col>
      <el-col :span="6"><el-form-item label="模型名称"> <el-input v-model="modelInfo.modelName" placeholder="模型名称" /></el-form-item></el-col>
      <el-col :span="6">
        <el-form-item label="模型能力">
          <el-select v-model="modelInfo.abilitiyList" placeholder="模型能力" multiple style="width: 100%">
            <el-option v-for="item in abilities" :value="item.value" :label="item.label" :key="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label-width="0" style="text-align: center">
      <el-button type="success" icon="el-icon-check" :loading="loading" @click="saveModel">模型{{modelInfo.modelId ? '更新' : '保存'}}</el-button>
    </el-form-item>
    <el-form-item label-width="0">
      <el-tabs v-model="activeName">
        <el-tab-pane v-if="selectDb && selectDb.dbId" label="应用表" name="dbTable">
          <app-schema-column select @rowSelect="columnSelect" @rowSelectAll="columnAllSelect" />
        </el-tab-pane>
        <el-tab-pane label="模型表" name="table">
          <model-table />
        </el-tab-pane>
        <el-tab-pane label="模型列" name="column">
          <model-column />
        </el-tab-pane>
        <el-tab-pane label="表关系"  name="join">
          <model-join />
        </el-tab-pane>
        <el-tab-pane v-if="modelInfo.modelId && modelInfo.mainColumn" label="模型数据" name="data" lazy>
          <model-data />
        </el-tab-pane>
      </el-tabs>
    </el-form-item>
  </el-form>
</template>

<script>
import ModelTable from "@/views/system/model/ModelTable";
import ModelColumn from "@/views/system/model/ModelColumn";
import ModelJoin from "@/views/system/model/ModelJoin";
import ModelData from "@/views/system/model/ModelData";
import AppSchemaColumn from "@/views/system/app/schema/AppSchemaColumn";
export default {
  name: "ModelInfo",
  components: { AppSchemaColumn, ModelData, ModelJoin, ModelColumn, ModelTable},
  provide(){
    return {
      abilities: this.abilities,
      modelInfo: this.modelInfo
    }
  },
  inject: {
    appContext: {
      from: 'appContext',
      default: function () {
        return {}
      }
    }
  },
  props: {
    modelInfo: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      activeName: 'table',
      abilities: [ {value:'*',label:'所有'},{value:'insert',label:'新增'},{value:'update',label:'更新'},{value:'delete',label:'删除'} ],
      selectDb: {}
    }
  },
  created() {
    this.loadModel()
  },
  methods: {
    dbChange() {
      this.$Util.cleanObj(this, this.selectDb)
      if (this.modelInfo.callDb) {
        const { allDbs, envObj } = this.appContext
        let db = allDbs.find(item => item.callCmd === this.modelInfo.callDb)
        if (db) {
          this.$Util.copyAttr(db, this.selectDb, null, this)
        } else if (envObj) {
          const value = envObj[this.modelInfo.callDb]
          db = allDbs.find(item => item.callCmd === value)
          if (db) {
            this.$Util.copyAttr(db, this.selectDb, null, this)
          }
        }
      }
    },
    loadModel(){
      const { modelId } = this.modelInfo
      if (!modelId) {
        this.$set(this.modelInfo, 'tables', [])
        this.$set(this.modelInfo, 'fields', [])
        this.$set(this.modelInfo, 'abilitiyList', [])
        this.$set(this.modelInfo, 'joins', [])
      } else {
        this.loading = true
        this.$get('model/get/' + modelId)
            .then(res => {
              this.$resultMsg(this, res, true)
              if (res.code === 200) {
                const { tables, fields, abilitiyList, joins } = res.data
                this.$set(this.modelInfo, 'tables', tables)
                this.$set(this.modelInfo, 'fields', fields)
                this.$set(this.modelInfo, 'joins', joins)
                this.$set(this.modelInfo, 'abilitiyList', abilitiyList)
              }
              this.dbChange()
              setTimeout(() => {
                this.loading = false
              }, 200)
            })
      }
    },
    saveModel() {
      this.loading = true
      this.$post('model/save', this.modelInfo)
          .then(res => {
            this.$resultMsg(this, res)
            if (res.code === 200) {
              this.$set(this.modelInfo, 'modelId', res.data.modelId)
              this.$emit('save')
              this.$emit('refreshTab', res.data)
            }
            setTimeout(() => {
              this.loading = false
            }, 200)
          })
    },
    columnSelect(row, all){
      const copy = this.$Util.copy(row)
      delete copy.columnId
      const { jdbcName, jdbcTable } = copy
      if (!this.modelInfo.tables) {
        this.$set(this.modelInfo,'tables', [])
      }
      // 添加表
      const tableIndex = this.modelInfo.tables.findIndex(item => item.jdbcName === jdbcTable )
      if (tableIndex < 0) {
        const table = { jdbcOrder: this.modelInfo.tables.length + 1, abilitiyList: ['*'], jdbcName: jdbcTable, jdbcAlias: `t${this.modelInfo.tables.length + 1}` }
        this.modelInfo.tables.push(table)
      }
      if (!this.modelInfo.fields) {
        this.$set(this.modelInfo,'fields', [])
      }
      const index = this.modelInfo.fields.findIndex(item => item.jdbcName === jdbcName && item.jdbcTable === jdbcTable )
      if (index < 0) {
        copy.jdbcOrder = this.modelInfo.fields.length + 1
        copy.abilitiyList = ['*']
        copy.jdbcAlias = copy.jdbcAlias || jdbcName
        this.modelInfo.fields.push(copy)
      } else {
        const old = this.modelInfo.fields[index]
        old.callDict = copy.callDict
        old.callRule = copy.callRule
        old.jdbcAlias = copy.jdbcAlias || jdbcName
        old.jdbcType = copy.jdbcType
        old.jdbcLength = copy.jdbcLength
        old.jdbcDigit = copy.jdbcDigit
        old.jdbcDefault = copy.jdbcDefault
        old.jdbcNullAble = copy.jdbcNullAble
        this.modelInfo.fields.splice(index, 1, old)
      }
      if (!all) {
        this.$resultMsg(this, { code: 200, msg:  index < 0 ? '添加成功': '替换成功'})
      }
    },
    columnAllSelect(list) {
      list.forEach(item => {
        this.columnSelect(item, true)
      })
      this.$resultMsg(this, { code: 200, msg: '全选完成'})
    }
  }
}
</script>

<style scoped>

</style>
